package com.coding.easier.translate;

import com.coding.easier.constant.TranslateConstant;
import com.coding.easier.enums.LanguagesEnum;
import com.coding.easier.util.*;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.project.Project;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.compile;

/**
 * @author: D丶Cheng
 * @description: 翻译基础类
 * @create: 2019-09-03 10:15
 **/
public abstract class AbstractTranslateAction extends AnAction {

    private static Logger logger = Logger.getInstance(AbstractTranslateAction.class);

    public static final Pattern p = compile("[\u4e00-\u9fa5]");

    public static LanguagesEnum localLan;
    public static Editor editor;
    public static Project project;
    public static SelectionModel selectionModel;

    static {
        switch (Locale.getDefault().getCountry()) {
            case "HK":
                localLan = LanguagesEnum.CHINESE_TRADITIONAL;
                break;
            case "TW":
                localLan = LanguagesEnum.CHINESE_TRADITIONAL;
                break;
            default:
                localLan = LanguagesEnum.CHINESE;
                break;
        }
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        try {
            String selectedText = "";
            if (editor == null) {
                selectedText = TranslateBalloon.origEditorPane.getSelectedText();
                selectedText = StringUtils.isEmpty(selectedText) ? TranslateBalloon.transEditorPane.getSelectedText() :
                        selectedText;
            }
            else {
                selectionModel = editor.getSelectionModel();
                selectedText = selectionModel.getSelectedText();
            }
            if (StringUtils.isEmpty(selectedText)) {
                NoticeUtil.error("请选择要翻译的字符");
                return;
            }
            NoticeUtil.init(this.getClass().getSimpleName(), 1);
            doTranslate(StringUtil.textToWords(selectedText));
        }
        catch (Exception e) {
            NoticeUtil.error(e);
        }
    }

    @Override
    public void update(AnActionEvent e) {
        project = e.getData(CommonDataKeys.PROJECT);
        editor = e.getData(CommonDataKeys.EDITOR);
        e.getPresentation().setVisible(project != null && editor != null
                && editor.getSelectionModel().hasSelection());
    }

    /**
     * 调用接口,翻译并返回值
     *
     * @param word
     * @param srcLan
     * @param targetLan
     * @param mEditor
     * @return
     * @throws Exception
     */
    public static GoogleTranslateResult translate(String word, String srcLan, String targetLan, Editor mEditor)
            throws Exception {
        String data = "q=" + URLEncoder.encode(word, "UTF-8");

        String translateUrl = getTranslateUrl(srcLan, targetLan, TkUtil.tk(word));
        logger.info("translateUrl===>" + translateUrl);
        logger.info("query data====>" + data);
        String result = "";

        try {
            result = HttpUtils.post(translateUrl, data);
            GoogleTranslateResult translateResult = GsonUtil.jsonToObject(result, GoogleTranslateResult.class);
            translateResult.setSuccess(true);
            return translateResult;
        }
        catch (Exception e) {
            GoogleTranslateResult translateResult = new GoogleTranslateResult();
            translateResult.setSuccess(false);
            translateResult.setMsg(e.getMessage());
            return translateResult;
        }
    }

    /**
     * 根据类型选择接口地址
     *
     * @param srcLan
     * @param targetLan
     * @param tk
     * @return
     */
    private static String getTranslateUrl(String srcLan, String targetLan, String tk) {
        return new UrlUtils(TranslateConstant.BASE_GOOGLE_TRANSLATE_URL)
                .addQueryParameter("sl", srcLan)
                .addQueryParameter("tl", targetLan)
                .addQueryParameter("client", "gtx")
                .addQueryParameter("dt", "t")
                .addQueryParameter("dt", "bd")
                .addQueryParameter("dt", "rm")
                .addQueryParameter("dt", "qca")
                .addQueryParameter("dj", "1")
                .addQueryParameter("ie", "UTF-8")
                .addQueryParameter("oe", "UTF-8")
                .addQueryParameter("hl", localLan.getCode())
                .addQueryParameter("tk", tk).build();
        //        if (translateType.equals(TranslateConstant.ZH_CN_TO_EN)) {
        //            return String.format(TranslateConstant.GOOGLE_TRANSLATE_URL, "zh-CN", "en", tk, word);
        //        }
        //        else {
        //            return String.format(TranslateConstant.GOOGLE_TRANSLATE_URL, "en", "zh-CN", tk, word);
        //        }
    }

    /**
     * 执行翻译
     *
     * @param selectText
     * @return
     */
    protected abstract void doTranslate(String selectText);

    /**
     * 文本弹出显示
     *
     * @param result
     * @param translateType
     */
    protected abstract void showPopupBalloon(GoogleTranslateResult result, String translateType);

}
